from flask import Flask, jsonify, request, redirect
from logic import CallOtherStorefaceDetAndEncodingToSQLAndMilvus
from pkg import GetImageArr
from config.cfg import Config
import os

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
app = Flask(__name__)

@app.route("/faceDetAndEncodeByURLToSQLAndMilvus", methods=["POST"])
def FaceDetAndEncodeByURLToSQLAndMilvus():
      url = request.form["url"]
      photoWeb = request.form["photoWeb"]
      # table = request.form["table"]
      if url[-3:] == "gif":
          return jsonify({"state":"fail", "info":"can't parse gif"})
      table = Config["mysql"]["table"]
      collection_name = Config["milvus"]["collection_name"]
      storerapi = Config["storerapi"]
      try:
          imgArr, info = GetImageArr(url)
      except Exception as r:
          return jsonify({"state":"fail", "info":"获取图片数组失败！找不到图片",})
      if len(imgArr) == 0:
          return jsonify({"state":"fail", "info":str(info),})
      return CallOtherStorefaceDetAndEncodingToSQLAndMilvus(imgArr, url, photoWeb, table, collection_name, storerapi)

@app.route("/getLogInfo", methods=["GET"])
def getLogInfo():
    count = readcount()
    return jsonify({"count":count})

def readcount():
    count=0
    with open("faceai.log", "r+") as f:
        while True:
            buffer=f.read(1024*8192)
            if not buffer:
                break
            count+=buffer.count('\n')
    return count


import re
import logging
from logging.handlers import TimedRotatingFileHandler 
from logging.handlers import RotatingFileHandler

def add_log_init(): 
    log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s'
    formatter = logging.Formatter(log_fmt)
    log_file_handler = TimedRotatingFileHandler(filename="faceai.log", when="D", interval=1, backupCount=7)
    log_file_handler.suffix = "%Y-%m-%d_%H-%M.log"
    log_file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")
    log_file_handler.setFormatter(formatter)
    log_file_handler.setLevel(logging.DEBUG)
    log = logging.getLogger()  
    log.addHandler(log_file_handler)
    app.run(host = "0.0.0.0",port=8802) 


if __name__ == "__main__":
      #app.run(host = "0.0.0.0",port=8802)
      add_log_init()


